<?php

class CoffeeRecommendController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to 'column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='column2';

	/**
	 * @var CActiveRecord the currently loaded data model instance.
	 */
	private $_model;

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
		array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array(/*'index','view',*/'recommend'),
				'users'=>array('*'),
		),
		//			array('allow', // allow authenticated user to perform 'create' and 'update' actions
		//				'actions'=>array(),
		//				'users'=>array('@'),
		//			),
		array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','view','reject','approve','delete',/*'update','create'*/),
				'roles'=>array('applyAdmin'),
		),
		array('deny',  // deny all users
				'users'=>array('*'),
		),
		);
	}

	public function actionApprove()
	{
		$coffeeShop=new CoffeeShop;
		$recommend=CoffeeRecommend::model()->findbyPk($_GET['id']);
		/* old style code - commented out (Sean 7-12-2011)
		$commonValues=array('name','ownerName','street','suburb','state','postcode',
		'country','website','phone','email','baristaNames','espressoMachine',
		'beansForSale','internetAccess','roastingOnSite','wifi', 'goodForBusiness','coffeeBrand',
		'day1Start','day1End','day2Start','day2End','day3Start','day3End','day4Start','day4End','day5Start','day5End','day6Start','day6End','day7Start','day7End');
		foreach($commonValues as $f){
			$coffeeShop->$f=$recommend->$f;
		}
		*/
		$coffeeShop->attributes = $recommend->attributes;
		$coffeeShop->review=$recommend->comment;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		$model=$coffeeShop;
		if(isset($_POST['CoffeeShop']))
		{
			if(isset($_POST['geo'])){
				$address=$model->street.', '.$model->suburb.' '.$model->state.', '.$model->postcode.', '.$model->country;
				$geo=Yii::app()->google->getGeoCode($address);
				if($geo['status']=='OK'){
					$result=$geo['results'][0];
					$oldAddress=$model->street.', '.$model->suburb.' '.$model->city.' '.$model->postcode.' '.$model->state.', '.$model->country
					.'. Location: '.$model->latitude.' '.$model->longitude;
					$streetNo='';
					$street='';
					foreach($result['address_components'] as $address_component){
						switch($address_component['types'][0]){
							case 'street_number':
								$streetNo = $address_component['long_name'];
								break;
							case 'route':
								$street = $address_component['long_name'];
								break;
							case 'locality':
								$model->suburb=$address_component['long_name'];
								break;
							case 'administrative_area_level_1':
								$model->state=$address_component['short_name'];
								break;
							case 'country':
								$model->country=$address_component['long_name'];
								break;
							case 'postal_code':
								$model->postcode=$address_component['long_name'];
								break;
						}
					}
					if($street){
						$model->street=$streetNo?($streetNo.' '.$street):$street;
					}
					$latlon=$result['geometry']['location'];
					$model->latitude=$latlon['lat'];
					$model->longitude=$latlon['lng'];

					Yii::app()->user->setFlash('coffee_update','<p>Geo information updated!</p>'
					.'<p>Old address was: '.$oldAddress.'</p>'
					.'<p>Please review the data and save it to make it persist!</p>');
				}else{
					Yii::app()->user->setFlash('coffee_update','Cannot update Geo information!  Check the address');
				}
			}else{
					
				$coffeeShop->attributes=$_POST['CoffeeShop'];
				$coffeeShop->timeUpdated=new CDbExpression('NOW()');
				$coffeeShop->timeCreated=time();
				if(isset($_POST['copy_day1'])){
					$coffeeShop->copyTimeFromDay1();
				}
				if($coffeeShop->validate()){
					$coffeeShop->save();
					$user=Yii::app()->user;
					$message='';
					if($user->isGuest){
						$message.='Guest User ';
					}else{
						$currentUser=User::model()->findByPk($user->id);
						$message.='User: '.$currentUser->username.' ('.$currentUser->id.') '."\n";
					}
					$message.='Approved Recommend for cafe: '.$coffeeShop->toSummaryString();
					Yii::log($message, CLogger::LEVEL_INFO,'mcr.coffeeshop.recommend');
			
					
					
					$recommend->status=CoffeeRecommend::STATUS_APPROVED;
					$recommend->shopId=$coffeeShop->id;
					if($recommend->save()){
						$email=$coffeeShop->email;
						$flashMessage='';
						$absUrl=$this->createAbsoluteUrl('coffeeShop/viewShop',array('id'=>$coffeeShop->id));
						if(!empty($email)){
							Yii::app()->mailer->sendOutgoingMail('approveCafe',$email,' YOUR CAFE HAS BEEN NOMINTED AS A POTENTIAL TOP 100 IN MELBOURNE',
							array('absUrl'=>$absUrl,'name'=>$recommend->name));
							$flashMessage.='Email has been sent to '.$email.' to notify about this approval. ';
						}
						$twitterSent=Yii::app()->twitter->setStatus("#coffee #{$coffeeShop->suburb} #{$coffeeShop->state} Welcome {$coffeeShop->name} to MCR, you've been recommended and added. View this cafe now at $absUrl");
						if($twitterSent){
							$flashMessage.='Twitter status updated!';						
						}
						Yii::app()->user->setFlash('adminMessage',$flashMessage);
					}
					$this->redirect(array('coffeeShop/view','id'=>$coffeeShop->id));
				}
			}
		}else{
			//not posted, find similar cafe
			//url:index-test.php/coffeeShop/listAll?CoffeeShop[name]=fr
			$name=trim($coffeeShop->name);
			
			$model=CoffeeShop::model();
			$criteria=new CDbCriteria;
			$criteria->compare('name',$name,true);
			$countExact=$model->count($criteria);
			if($countExact>0){
				Yii::app()->user->setFlash('coffee_update','There is already a cafe named '.CHtml::link($name,array('coffeeShop/listAll','CoffeeShop[name]'=>$name)).'.',array('target'=>'_blank'));
			}else{
				$nameTokens=split(' ',$name);
				$countResult=array();
				foreach($nameTokens as $namePart){
					$criteria=new CDbCriteria;
					$criteria->compare('name',$namePart,true);
					$countExact=$model->count($criteria);
					if($countExact > 0){
						$countResult[$namePart]=$countExact;
					}
				}
				$message="Search DB for cafe match this name.... <br />No Exact Mactch! Partial Match result:<br />";
				if(count($countResult)>0){
					foreach($countResult as $namePart=>$countName){
						$message.=CHtml::link($namePart." ($countName)",array('coffeeShop/listAll','CoffeeShop[name]'=>$namePart),array('target'=>'_blank'));
						$message.=' ';
					}
				}else{
					$message.='No Partial Match! Feel free to add this cafe!';
				}
				Yii::app()->user->setFlash('coffee_update',$message);
			
			}
		}

		$this->render('approve',array(
			'model'=>$coffeeShop,
		//'recommend'=>$recommend,
		));
	}

	/**
	 * Displays a particular model.
	 */
	public function actionView()
	{
		$this->render('view',array(
			'model'=>$this->loadModel(),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new CoffeeRecommend;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['CoffeeRecommend']))
		{
			$model->attributes=$_POST['CoffeeRecommend'];

			if($model->save())
			$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	public function actionRecommend(){
		if(Yii::app()->request->isIPhone()){
			$this->redirect(array('mobile/recommend'));
			return;
		}
		$model=new CoffeeRecommend;
		$model->country='Australia';
		if(isset($_GET['name'])){
			$model->name=$_GET['name'];
		}
		if(isset($_GET['suburb'])){
			$model->suburb=$_GET['suburb'];
		}
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['CoffeeRecommend']))
		{
			$model->attributes=$_POST['CoffeeRecommend'];
			$model->fromIp=$_SERVER['REMOTE_ADDR'];
			$model->date=time();
			$model->status=CoffeeRecommend::STATUS_PENDING;
			$model->shopId=null;

			if($model->save()){
				Yii::app()->user->setFlash('coffeeRecommend','Thank you. Your recommendation has been processed!');
				@Yii::app()->mailer->sendOutgoingMail('alertEmail',Yii::app()->params['alertEmail'],'Auto Alert: cafe recommend',
				array(
					'event'=>array(
						'event'=>'A new cafe is recommended',
						'name'=>$model->name
					)
				));
				$this->redirect(array('recommend'));


			}
		}

		$this->render('recommend',array(
			'model'=>$model,
		));
	}

	public function actionReject(){
		$model=$this->loadModel();
		$model->status=CoffeeRecommend::STATUS_REJECTED;
		$model->save();
		$user=Yii::app()->user;
		$message='';
		if($user->isGuest){
			$message.='Guest User ';
		}else{
			$currentUser=User::model()->findByPk($user->id);
			$message.='User: '.$currentUser->username.' ('.$currentUser->id.') '."\n";
		}
		$message.='Rejected Recommend for cafe: '.$model->name . ' (recommend id: '.$model->id.')';
		Yii::log($message, CLogger::LEVEL_INFO,'mcr.coffeeshop.recommend');
		$this->redirect(array('admin'));
	}




	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionUpdate()
	{
		$model=$this->loadModel();

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['CoffeeRecommend']))
		{
			$model->attributes=$_POST['CoffeeRecommend'];

			if($model->save())
			$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 */
	public function actionDelete()
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel()->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_POST['ajax']))
			$this->redirect(array('index'));
		}
		else
		throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('CoffeeRecommend');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new CoffeeRecommend('search');

		if(isset($_GET['CoffeeRecommend']))
		$model->attributes=$_GET['CoffeeRecommend'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 */
	public function loadModel()
	{
		if($this->_model===null)
		{
			if(isset($_GET['id']))
			$this->_model=CoffeeRecommend::model()->findbyPk($_GET['id']);
			if($this->_model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		}
		return $this->_model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='coffeerecommend-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
